<?php
namespace App\Services\Factory\Payment;

use App\Common\Constant\Params;
use App\Services\Factory\PaymentFactory;
use App\Services\IWeixinService;
use CLogFileHandler;
use JsApiPay;
use PayNotifyCallBack;
use WxPayApi;
use WxPayLog;
use WxPayUnifiedOrder;

/**
 * 微信支付
 * Class WxPay
 */
class WxPay extends PaymentFactory
{

    private $tools;

    /**
     * WxPay constructor.
     */
    public function __construct()
    {
        defined('WXPAY_APP_ID') or define('WXPAY_APP_ID',config('services.Wxpayappid'));
        defined('WXPAY_APP_SECRET') or define('WXPAY_APP_SECRET',config('services.WxpayAppSecret'));
        defined('WXPAY_MCHID') or define('WXPAY_MCHID',config('services.WxpayMchid'));
        defined('WXPAY_KEY') or define('WXPAY_KEY',config('services.WxpayKey'));

        require_once(app_path('Libs/WxpaySdk/lib/WxPay.Api.php'));
        require_once(app_path('Libs/WxpaySdk/WxPay.JsApiPay.php'));
        require_once(app_path('Libs/WxpaySdk/log.php'));

        //初始化日志
        $logfile = storage_path('logs/wxpay-'.date('Y-m-d').'.log');
        $logHandler= new CLogFileHandler($logfile);
        WxPayLog::Init($logHandler, 15);

        $this->tools = new JsApiPay();
    }

    public function form($order_number, $amount, $redirect_url, $description,array $attach)
    {

        $openId = resolve(IWeixinService::class)->useridToOpenid(getCurrentWeixinUserid());

//②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($description);
        $input->SetAttach(json_encode($attach));
        $input->SetOut_trade_no($order_number);
        $input->SetTotal_fee($amount*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
//        $input->SetGoods_tag("test");
        $input->SetNotify_url(url('callback/wxpay'));
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $this->tools->GetJsApiParameters($order);

//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
        /**
         * 注意：
         * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
         * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
         * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
         */

        return view('payform/wxpay',[
            'jsApiParameters'=>$jsApiParameters,
            'trade_number'=>$order_number,'amount'=>$amount,'payment_method'=>Params::PAY_METHOD_WEIXIN,
            'redirect_url'=>$redirect_url,
        ]);
    }

    public function notify()
    {
        $this->log("2.Resolving notify");
        require_once(app_path('Libs/WxpaySdk/lib/WxPay.Notify.php'));
        require_once(app_path('Libs/WxpaySdk/notify.php'));

        $notify = new PayNotifyCallBack();
        return $notify->Handle(false) ? : [null,null,null];
    }

    public function log($message)
    {
        WxPayLog::DEBUG($message);
    }

}